//
//  EmoticonKeyboardView.swift
//  EmoticonKeyBoard
//
//  Created by apple on 15/12/26.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit

private let toolBarHeight: CGFloat = 35
private let EmoticonCellId = "EmoticonCellId"

class EmoticonKeyboardView: UIView {
    
    //添加分组表情数据的属性
    private lazy var packages = EmoticonsManager().packages

    //定义事件回掉的闭包 就相当于 代理 
    var selectEmoticonBlock: ((en: Emoticon) -> ())?
    
    @objc func itemDidClick(item:UIBarButtonItem) {
        print(item.tag)
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        //让视图滚到到对应的位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    // MARK:定义外部模型属性
    
    
    // MARK:重写构造方法
    init(selectEmotion: (en: Emoticon) -> ()) {
        //记录外部传递参数 闭包
        
        self.selectEmoticonBlock = selectEmotion
        
        let cgrect = CGRect(x: 0, y: 0, width:UIScreen.mainScreen().bounds.width , height: 220)
        super.init(frame: cgrect)
        setupUI()
        backgroundColor = UIColor.redColor()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:设置页面和布局
    private func setupUI() {
        addSubview(toolBar)
        addSubview(collectionView)
        //设置约束
    
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self)
            make.height.equalTo(toolBarHeight)
        }
        
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.left.right.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        //设置工具条
        setToolBar()
        
    }
    
    private func setToolBar() {
        //设置文字颜色
        toolBar.tintColor = UIColor.lightGrayColor()
        var items = [UIBarButtonItem]()
        var index = 0
        
        for p in packages {
        
            let item = UIBarButtonItem(title: p.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "itemDidClick:")
            //添加到数组中
            items.append(item)
            items.last?.tag = index++
            
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        toolBar.items = items
    }
    
    // MARK:懒加载所有的子视图
    private lazy var toolBar: UIToolbar = UIToolbar()
    private lazy var collectionView: UICollectionView = {
        //实例化流水布局
        let layout = UICollectionViewFlowLayout()
        let itemW = UIScreen.mainScreen().bounds.width / 7
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        //调整sectionInset
        let margin = (self.bounds.height - toolBarHeight - 3 * itemW) / 4
        layout.sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        //设置layout的滚动方向
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        let cv = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        //注册cell 
        cv.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellId)

        cv.backgroundColor = UIColor.whiteColor()
        //取消弹簧效果
        cv.bounces = false
        //设置数据源
        cv.dataSource = self
        //设置代理
        cv.delegate = self
        //设置枫叶
        cv.pagingEnabled = true
        return cv
    }()
}

extension EmoticonKeyboardView: UICollectionViewDataSource , UICollectionViewDelegate {
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticones.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellId, forIndexPath: indexPath) as! EmoticonCell
    
        //在这个地方 可以获取到单个emoticon 模型数据
        cell.emoticon = packages[indexPath.section].emoticones[indexPath.item]
        
        return cell
    }
    
    //点击某个item的协议方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let em = packages[indexPath.section].emoticones[indexPath.item]
        //在实例化方法中 保存了一个 属性闭包
        //执行闭包
        
        selectEmoticonBlock?(en: em)
    }
}

class EmoticonCell: UICollectionViewCell {
    
    // MARK:定义外部模型属性
    
    var emoticon: Emoticon? {
        didSet {
            print("--")
            print(emoticon?.iamgePath)
           print("--")
            emoticonBtn.setImage(UIImage(contentsOfFile: emoticon?.iamgePath ?? ""), forState: UIControlState.Normal)
        
            emoticonBtn.setTitle(emoticon?.emojiStr ?? "", forState: UIControlState.Normal)
        
            if let em = emoticon where em.isDelete {
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
        }
    }
    
    // MARK:重写构造方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:设置页面和布局
    private func setupUI() {
        
        addSubview(emoticonBtn)
        emoticonBtn.backgroundColor = UIColor.whiteColor()
        
        //设置btn的frame
        emoticonBtn.frame = CGRectInset(bounds, 4, 4)
        emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        emoticonBtn.setTitleColor(UIColor.darkTextColor(), forState: UIControlState.Normal)
        //设置按钮不可交互
        emoticonBtn.userInteractionEnabled = false
    }
    
    // MARK:懒加载所有的子视图
    lazy var emoticonBtn: UIButton = UIButton()

}











